package com.example.softwareconfigurationcoursedesign;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class LogDaoimpl implements LogDao {
    public List<Logs> queryLog(String UserId) {
        if (UserId == null) {
            return null;
        }
        Connection conn = DBHelper.getConnection();
        String sql = "select * from Logs WHERE user_id='" + UserId + "';";
        PreparedStatement stat = null;
        ResultSet rs = null;
        List<Logs> logslist = new ArrayList<Logs>();
        try {
            stat = conn.prepareStatement(sql);
            rs = stat.executeQuery();
            while (rs.next()) {
                Logs log = new Logs();
                log.setUserId(rs.getString("user_id"));
                log.setUserName(rs.getString("username"));
                log.setLoginMethod(rs.getString("login_method"));
                log.setTimes(rs.getString("login_time"));
                log.setLogContext(rs.getString("event"));
                logslist.add(log);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stat, rs);
        }
        if (logslist.isEmpty())
            return null;
        else
            return logslist;
    }

    @Override
    public void addLog(Logs log) {
        Connection conn = DBHelper.getConnection();
        String sql = "INSERT Logs (user_id,username,login_method,login_time,event) VALUE(?,?,?,?,?);";
        PreparedStatement stat = null;
        ResultSet rs = null;
        try{
            stat = conn.prepareStatement(sql);
            stat.setString(1,log.getUserId());
            stat.setString(2,log.getUserName());
            stat.setString(3,log.getLoginMethod());
            stat.setString(4,log.getTimes());
            stat.setString(5,log.getLogContext());
            stat.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBHelper.closeAll(conn,stat,rs);
        }
    }
}

